package com.springcloud.alibaba.consumer.controller;

import com.springcloud.albaba.common.entity.Commentresult;
import com.springcloud.albaba.common.entity.Payment;
import com.springcloud.alibaba.consumer.lib.LoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @Author:RenPu
 * @Date: 2020/6/30 10:48
 * @Version: 1.0
 * @description:
 */

@RestController
@Slf4j
public class ConsumerController {

    private static final String INOVK_URL="http://consul-payment-server";

    @Resource
    private RestTemplate restTemplate;


    //测试手写轮询算法所需要的依赖
    @Resource
    private LoadBalance loadBalance;

    @Resource
    private   DiscoveryClient discoveryClient;


    @GetMapping(value = "/consumer/payment/consul")
    public String getConsulPaymentMessage(){
       String result = (String) restTemplate.getForObject(INOVK_URL+"/payment/consul",String.class);

//        ResponseEntity<Commentresult> forEntity = restTemplate.getForEntity( INOVK_URL + "/payment/consul", Commentresult.class );
        return result;
    }


    //测试手写轮询算法
    @GetMapping("/consumer/lb")
    public String getServerPort(){
        List<ServiceInstance> instances = discoveryClient.getInstances( "consul-payment-server" );

        ServiceInstance instance = loadBalance.instance( instances );
        URI uri = instance.getUri();

        return restTemplate.getForObject(uri+"/payment/consul",String.class);

    }



}
